package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.City;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.Player;
import com.vincce.sport.entity.School;
import com.vincce.sport.mapper.CityMapper;
import com.vincce.sport.mapper.SchoolMapper;
import com.vincce.sport.mapper.ZoneMapper;

@Controller
@RequestMapping("/school")
public class SchoolController extends BaseController{
	@Resource
	private CityMapper cityMapper;
	@Resource
	private ZoneMapper zoneMapper;
	@Resource
	private SchoolMapper schoolMapper;
	
	/**
	 * 分页查询
	 * @param model
	 * @param page
	 * @param city
	 * @return
	 */
	@RequestMapping("/schoolList")
	public String queryCityByPage(Model model,Page<School> page,School school){
		Map<String, Object> filter = new HashMap<String, Object>();
		if(school.getName() != null && !school.getName().equals("")){
	            filter.put("name", school.getName());
	    }
		if(school.getZoneId() != null && !school.getZoneId().equals("")){
            filter.put("zoneId", school.getZoneId());
        }
		
		if(school.getCityId() != null && !school.getCityId().equals("")){
            filter.put("cityId", school.getCityId());
        }
		page.setFilter(filter);
		page.setTotal(schoolMapper.querySchoolCount(page.getFilter()));
		page.setResult(replace(schoolMapper.querySchoolByPage(page)));
		
		model.addAttribute("zoneList",zoneMapper.queryByZoneAll());
		model.addAttribute("cityList",cityMapper.queryByCityAll());
		model.addAttribute("school",school);
		model.addAttribute("page",page);
		return "/backstage/schoolList";
	}
	
	
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<School> replace(List<School> imgTempList){
		if(imgTempList!=null && imgTempList.size()>0){
			for(School itl:imgTempList){
				itl.setLogoUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+itl.getLogoUrl(), "ori"));
			}
		}
		return imgTempList;
	}
	
	/**
	 * 新增
	 * @param model
	 * @param school
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/addSchool")
	@ResponseBody
	public String insertSchool(Model model,School school,@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		
		Long count=0L;
		Map<String, Object> result = new HashMap<String, Object>();
	    SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
		if (file != null && !file.isEmpty()) {
			String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
        		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
        		result.put("suc", false);
            }else{
            	obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                if (obj.statusCode == 200) {
                	
                	String path = obj.info.replaceAll("\\\\", "/");
                	result.put("img", String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+path, "ori"));
                	//result.put("imgPath", path);
                	school.setLogoUrl(path);
                	school.setCreateUser(getCurrentUser().getId().intValue());
            		school.setCreateTime(new Date());
            		school.setUpdateTime(new Date());
            		school.setUpdateUser(getCurrentUser().getId().intValue());
                	count=schoolMapper.insertSchool(school);
                }
                	
            }
		}else{
        	result.put("msg","请选择文件!");
            result.put("suc", false);
        }
		
		
		
		result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 修改
	 * @param model
	 * @param school
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updateSchool")
	@ResponseBody
	public String updateSchool(Model model,School school,@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		Long count=0L;
		Map<String, Object> result = new HashMap<String, Object>();
		SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
		if (file != null && !file.isEmpty()) {
        	String fileName = file.getOriginalFilename();
        	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
        		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
        		result.put("suc", false);
			}else{
				obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                if (obj.statusCode == 200) {
                	String path= obj.info.replaceAll("\\\\", "/");
                	school.setLogoUrl(path);
                	school.setUpdateTime(new Date());
            		school.setUpdateUser(getCurrentUser().getId().intValue());
                	count = schoolMapper.updateSchool(school);
                }
			}
        } else {
        	school.setUpdateTime(new Date());
        	school.setUpdateUser(getCurrentUser().getId().intValue());
        	count = schoolMapper.updateSchool(school);
        }
		result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	
	
	
	/**
	 * 根据ID删除
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(Model model,Integer id){
		Boolean flag=false;
		Integer count=schoolMapper.deleteById(id);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}
	
	@RequestMapping("/querySchoolByCityId")
	@ResponseBody
	public String querySchoolByCityId(Model model,Integer cityId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cityId", cityId);
		List<School> list=schoolMapper.queryByCityId(map);
        return JSON.toJSONString(list);
	}

}
